#ifndef XHCPCONNECTION_H
#define XHCPCONNECTION_H

#include <QObject>
#include <QTcpSocket>
#include <QString>
#include <QHostAddress>

class XHCPConnection : public QObject
{
    Q_OBJECT
public:
    /*
    1xx : An informational response, e.g. for help text etc.
    2xx : A successful response.
    3xx : An operation is in progress, and the client must send further data to complete the operation.
    4xx : An operation has failed.
    5xx : An error has occurred.
    6xx : Replication-specific codes. Only valid for connections in REPL mode.
    9xx : A debug response - these should be ignored by applications and are for use only by the development team.
     */
    typedef enum {
        INFORMATION = 0x01,
        SUCCESS = 0x02,
        INPROGRESS = 0x03,
        FAIL = 0x04,
        ERROR = 0x05,
        REPLICATION = 0x06,
        //...
        DEBUG = 0x09
    } MessageType;

private:
    const static int DEFAULT_XHCP_PORT = 3865;
    QTcpSocket* m_socket;
    QString m_connectionName;
    QString m_errorMessage;
    QHostAddress m_hostAddress;
    int m_port;
    QString m_pendingData;

    bool sendData(QByteArray data);

public:
    XHCPConnection(const QString& connectionName, QObject* parent = 0);
    ~XHCPConnection();

    void setHostAddress(const QHostAddress& address) { m_hostAddress = address; }
    const QHostAddress& getHostAddress() const { return m_hostAddress; }
    int getPort() const { return m_port; }
    void setPort(int port) { m_port = port; }

    void setConnectionOptions(const QHostAddress& host, int port = DEFAULT_XHCP_PORT);
    bool isOpen() const;
    const QString& getErrorMessage() const { return m_errorMessage; }

    const QString& getConnectionName() const { return m_connectionName; }
    void setConnectionName(const QString& connectionName) { m_connectionName = connectionName; }

private slots:
    void onServerConnected();
    void onServerDisconnected();
    void onServerDataReceived();
    void onServerError(QAbstractSocket::SocketError);

public slots:
    void open();
    void close();


    void requestListAllDevs();

signals:
    void s_connected();
    void s_disconnected();
    void s_error();
};

#endif // XHCPCONNECTION_H
